package com.qincji.webviewbrowser.slice;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.orhanobut.hawk.Hawk;
import com.qincji.webviewbrowser.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.*;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.media.image.PixelMap;

public class MainAbilitySlice extends AbilitySlice {

    private final static String TAG = "MainAbilitySlice";

    private final static String JS_NAME = "JsCallJava";

    private Navigator navigator;
    private String url;
    private boolean isActiveTitle;
    private TopBar topBar;
    private String title;
    private ProgressBar progressBar;
    private WebView webView;
    private String curUrl;


    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        Logs.i(TAG, "onOrientationChanged：" + displayOrientation.name());
        if (displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE) {//如果是横屏则请求全屏
            if (topBar != null) {
                topBar.hid();
                getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
            }
        } else {
            if (topBar != null) {
                topBar.show();
                getWindow().clearFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
            }
        }
        super.onOrientationChanged(displayOrientation);
    }


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //获取传递过来的标题
        title = intent.getStringParam(MainAbility.TITLE);
        url = intent.getStringParam(MainAbility.URL);//获取传递过来的url
        curUrl = url;
        isActiveTitle = intent.getBooleanParam(MainAbility.ACTIVE_TITLE, false);
        topBar = new TopBar(this, title, component -> {
            backOrClose();
        }, ResourceTable.Media_more, null, component -> {
            if (navigator == null) {
                return;
            }
            MoreDialog.showPop(getContext(), item -> {
                switch (item) {
                    case 0://分享
                        Logs.d(TAG, "getFirstRequestUrl: " + webView.getFirstRequestUrl());
                        AppKit.shareText(getAbility(), webView.getTitle() + " " + curUrl + " 来自「Qincji」");
                        break;
                    case 1://在浏览器中打开
                        AppKit.openInBrowser(getAbility(), curUrl);
                        break;
                    case 2://刷新
                        webView.reload();
                        break;
                    case 3://后退
                        if (navigator.canGoBack()) {
                            navigator.goBack();
                        }
                        break;
                    case 4://前进
                        if (navigator.canGoForward()) {
                            navigator.goForward();
                        }
                        break;
                    case 5://关闭 webview
                        terminate();
                        break;
                    default:
                        break;
                }
            });
        });
        progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progress_bar);
//        setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED);
        initVebView();
    }

    private void initVebView() {
        webView = (WebView) findComponentById(ResourceTable.Id_webView);
        webView.setWebAgent(new WebAgent() {

            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                String scheme = request.getRequestUrl().getScheme();
                Logs.d(TAG, "isNeedLoadUrl: " + scheme);
                if (scheme != null && (scheme.contains("alipay") || scheme.contains("mq")
                        || scheme.contains("tencent") || scheme.contains("wechat") || scheme.contains("weixin")
                        || scheme.contains("baidu") || scheme.contains("bilibili") || scheme.contains("new")
                        || scheme.contains("orpheuswidget") || scheme.contains("yddict") || scheme.contains("ntesopen")
                        || scheme.contains("12306") || scheme.contains("iosamap") || scheme.contains("weibo")
                        || scheme.contains("youku") || scheme.contains("iqiyi") || scheme.contains("tudou")
                        || scheme.contains("pptv") || scheme.contains("kugou") || scheme.contains("zhihu"))) {
                    return false;//不进行拦截的Scheme
                }
                // 增加开发者自定义逻辑
                return super.isNeedLoadUrl(webView, request);
            }

            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
                super.onLoadingPage(webView, url, favicon);
                // 页面开始加载时自定义处理
                progressBar.setVisibility(Component.VISIBLE);
                progressBar.setProgressValue(5);
                curUrl = url;
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                // 页面加载结束后自定义处理
                progressBar.setVisibility(Component.HIDE);
            }

            @Override
            public void onLoadingContent(WebView webView, String url) {
                super.onLoadingContent(webView, url);
                // 加载资源时自定义处理
//                webView.load(url);
            }

            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
                // 发生错误时自定义处理
                Logs.e(TAG, "onError..." + error);
            }
        });
        webView.setBrowserAgent(new BrowserAgent(this) {
            @Override
            public void onTitleUpdated(WebView webView, String title) {
                super.onTitleUpdated(webView, title);
                // 标题变更时自定义处理
                if (isActiveTitle) {
                    topBar.setTitle(title);
                }
            }

            @Override
            public void onProgressUpdated(WebView webView, int newProgress) {
                super.onProgressUpdated(webView, newProgress);
                // 加载进度变更时自定义处理
                progressBar.setProgressValue(newProgress);
                if (newProgress == 100) {//加载结束
                    progressBar.setVisibility(Component.HIDE);
                } else {
                    progressBar.setVisibility(Component.VISIBLE);
                }
            }
        });

        /**
         * 配置JS发来的消息处理。
         * 如js中调用：var appResp = window.JsCallJava.call("{\"type\": \"is_login\"}");
         * 其中，jsStr对应"{\"type\": \"is_login\"}"
         * appResp对应responseWeb(6002, "未登录")
         */
        webView.addJsCallback(JS_NAME, jsStr -> {
            // 处理接收到的Js发送来的消息
            Logs.d(TAG, "接收到前端的请求：" + jsStr);
            //处理web前端传递过来的数据
            JsonObject req = new Gson().fromJson(jsStr, JsonObject.class);
//            JsonObject req = new JsonParser().parse(str).getAsJsonObject();
            String type = req.get("type").getAsString();
            Logs.d(TAG, "type：" + type);
            if ("set_cookie".equals(type)) {
                JsonObject data = req.getAsJsonObject("data");
                String name = data.get("name").getAsString();
                String value = data.get("value").getAsString();
                if (name != null && value != null && !name.isEmpty() && !value.isEmpty()) {
                    Hawk.put(HawkKey.COOKIE, data);
                    Logs.d(TAG, "设置cookie成功：" + name + " | " + value);
                    setCookies();
                } else {
                    return responseWeb(6001, "获取cookie数据异常");
                }
            } else if ("is_login".equals(type)) {
                if (Hawk.contains(HawkKey.COOKIE)) {
                    return responseWeb(200, "已登录");
                } else {
                    return responseWeb(6002, "未登录");
                }
            }

            return responseWeb(200, "发送成功");
        });

        setCookies();//从以前获取的cookie重新设置

        //https://developer.harmonyos.com/cn/docs/documentation/doc-references/webconfig-0000001138633149
        WebConfig webConfig = webView.getWebConfig();
        webConfig.setWebStoragePermit(true);//DOM Storage
        webConfig.setJavaScriptPermit(true);//启用js
        webConfig.setLoadsImagesPermit(true);//解决图片不显示
        webConfig.setMediaAutoReplay(true);
        webConfig.setMediaAutoReplay(true);
        webConfig.setDataAbilityPermit(true);
        webConfig.setTextAutoSizing(true);
        webConfig.setSecurityMode(WebConfig.SECURITY_ALLOW);
        webConfig.setViewPortFitScreen(true);
//        webConfig.setUserAgent();
        navigator = webView.getNavigator();
        webView.load(url);
    }

    @Override
    protected void onBackPressed() {
//        super.onBackPressed();//拦截返回
        backOrClose();
    }

    @Override
    protected void onStop() {
        Logs.i(TAG, "onStop...");
        if (webView != null) {
            webView.removeJsCallback(JS_NAME);
        }
        super.onStop();
    }

    private void backOrClose() {
        if (navigator != null && navigator.canGoBack()) {
            navigator.goBack();
        } else {
            terminate();
        }
    }

    private String responseWeb(int code, String message) {
        JsonObject resp = new JsonObject();
        resp.addProperty("code", code);
        resp.addProperty("message", message);
        String respData = new Gson().toJson(resp);
        Logs.d(TAG, "响应给前端：" + respData);
        return respData;
    }

    private void setCookies() {
        JsonObject data = Hawk.get(HawkKey.COOKIE, null);
        if (data == null) {
            return;
        }
        String name = data.get("name").getAsString();
        String value = data.get("value").getAsString();
        MyCookieStore cookieStore = new MyCookieStore();
        cookieStore.setCrossDomainCookieEnable(webView, true);
        cookieStore.setCookieEnable(true);
        cookieStore.setCookie(name, value);
    }

    private static class MyCookieStore extends CookieStore {

        @Override
        public void setCookieEnable(boolean b) {

        }

        @Override
        public void removeCookies(boolean b, AsyncCallback<Boolean> asyncCallback) {

        }

        @Override
        public String getCookie(String s) {
            return null;
        }

        @Override
        public void persist() {

        }

        @Override
        public void setCookie(String s, String s1) {

        }

        @Override
        public void setCrossDomainCookieEnable(WebView webView, boolean b) {

        }

        @Override
        public boolean isCookieEnable() {
            return false;
        }

        @Override
        public boolean isCrossDomainCookieEnable(WebView webView) {
            return false;
        }

        @Override
        public boolean hasCookies() {
            return false;
        }
    }
}
